import store from '@/store'
import { Auth } from '@/store/reducer/user'
import { Toast } from 'antd-mobile'
import axios from 'axios'
import history from './history'
import { getTokenInfo, removeTokenInfo, setTokenInfo } from './storage'

// 请求基地址
export const baseURL = 'http://geek.itheima.net'

const http = axios.create({
  baseURL: baseURL,
  timeout: 50000,
})

// 请求拦截器
http.interceptors.request.use(
  function (config: any) {
    const { token } = getTokenInfo()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
http.interceptors.response.use(
  function (response) {
    return response.data
  },
  async function (error) {
    console.dir(error)

    if (!error.response) {
      Toast.show({ content: '无网' })
    } else if (error.response.status !== 401) {
      Toast.show({ content: error.response.data.message })
    } else {
      const { refresh_token } = getTokenInfo()

      if (refresh_token) {
        try {
          // 根据 refresh_token 获取新 token
          const res = await axios({
            url: baseURL + '/v1_0/authorizations',
            method: 'put',
            headers: {
              Authorization: 'Bearer ' + refresh_token,
            },
          })
          console.log(res)
          const newToken = res.data.data.token
          const auth: Auth = { token: newToken, refresh_token }
          setTokenInfo(auth)

          store.dispatch({ type: 'user/saveAuth', payload: auth })

          // axios({
          //   ...error.config,
          //   headers: {
          //     ...error.config.headers,
          //     Authorization: 'Bearer ' + newToken,
          //   },
          // })
          return http(error.config)
        } catch (error) {
          Toast.show({ content: '信息过期，请重新登录' })
          removeTokenInfo()
          history.push('/login', { from: history.location.pathname })
        }
      }
      return Promise.reject(error)
    }
  }
)

export default http
